<template>
  <section :style="{backgroundColor:mode==='table'?'#f0f0f0':''}">
    <div v-show="mode==='chart'" class="chart">
      <div class="left">
        <Module id="allCameraInfo" :cfg="moduleCfg.allCameraInfo">
          <div style="width: 100%;height: 100%"></div>
        </Module>
        <Module id="errorAndFixCount" :cfg="moduleCfg.errorAndFixCount">
          <div style="width: 100%;height: 100%"></div>
        </Module>
      </div>
      <div class="right">
        <Module id="errorCameraInfo" :cfg="moduleCfg.errorCameraInfo">
          <div style="width: 100%;height: 100%"></div>
        </Module>
        <Module id="brandErrorInfo" :cfg="moduleCfg.brandErrorInfo">
          <div style="width: 100%;height: 100%"></div>
        </Module>
      </div>
    </div>
    <div class="tableBox" v-show="mode==='table'">
      <TableList :list="list" :column="column" :rowClick="rowClick">
        <div slot="column2" class="noBlueBg">
          <el-table-column
            prop="longitude"
            align="center"
            width="250"
            label="操作">
            <template slot-scope="scope">
              <div v-if="(identityId==='2' && scope.row.eventTypeTwoCode!=='-1') || (identityId==='5' && scope.row.eventTypeTwoCode!=='-1')" style="display: inline-block;">
                <el-button type="primary" plain size="mini" @click.stop="rowClick(scope.row)"
                           v-if="scope.row.state===1">稽核
                </el-button>
                <el-button type="success" plain size="mini" @click.stop="rowClick(scope.row)"
                           v-if="scope.row.state===2">发布
                </el-button>
                <el-button type="danger" plain size="mini" @click.stop="rowClick(scope.row)" v-if="scope.row.state===2">
                  忽略
                </el-button>
                <el-button type="warning" plain size="mini" @click.stop="examine(scope.row)" v-if="scope.row.state===4 && scope.row.orderEndTime">
                  审核
                </el-button>
              </div>
              <el-button class="ml10"
                         size="mini"
                         @click.stop="goTo(scope.row['bscCamera'].longitude,scope.row['bscCamera'].latitude)">到这去
              </el-button>
            </template>
          </el-table-column>


          <el-table-column
            prop="groupName"
            align="center"
            width="150"
            label="所属中心">
          </el-table-column>

          <el-table-column
            prop="location"
            align="center"
            width="150"
            label="路段">
            <template slot-scope="scope">
              {{scope.row['bscCamera'] && scope.row.bscCamera.road}}
            </template>
          </el-table-column>

          <el-table-column
            prop="name"
            align="left"
            label="设备名称">
            <template slot-scope="scope">
              {{scope.row['bscCamera'] && scope.row.bscCamera.name}}
            </template>
          </el-table-column>

          <el-table-column
            prop="groupValue"
            align="center"
            label="分组">
            <template slot-scope="scope">
              {{scope.row['bscCamera'] && scope.row['bscCamera']['groupValue']}}/{{ scope.row['bscCamera'] &&
              getTypeName(scope.row['bscCamera']['groupType'])}}
            </template>
          </el-table-column>

          <el-table-column
            prop="manufacturer"
            width="200"
            align="center"
            label="类型">
            <template slot-scope="scope">
              {{getEvtName(dict['event'][scope.row.eventTypeTwoCode])}}
            </template>
          </el-table-column>

          <el-table-column
            prop="manufacturer"
            align="center"
            width="200"
            label="状态">
            <template slot-scope="scope">
              {{dict['status'][scope.row.state]}}
            </template>
          </el-table-column>

          <el-table-column
            prop="removeTime"
            align="center"
            width="200"
            label="检测/消除时间">
            <template slot-scope="scope">
              {{scope.row['detectedTime']}}<br>
              {{scope.row['removeTime']}}
            </template>
          </el-table-column>

          <el-table-column
            prop="longitude"
            align="center"
            width="120"
            label="工单详情">
            <template slot-scope="scope">
              <el-button class="ml10"
                         size="mini"
                         @click.stop="viewInfo(scope.row)">查看
              </el-button>
            </template>
          </el-table-column>


        </div>
        <div slot="option" class="noBlueBg">
          <el-form :inline="true" :model="options" class="demo-form-inline" ref="optionForm">
            <el-form-item label="路段" prop="name">
              <el-input size="mini" v-model="options.name" clearable placeholder="请输入路段"></el-input>
            </el-form-item>
            <!--            <el-form-item label="安装位置" prop="location">-->
            <!--              <el-input size="mini" v-model="options.location" clearable placeholder="请输入安装位置"></el-input>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="品牌" prop="brand">-->
            <!--              <el-input size="mini" v-model="options.brand" clearable placeholder="请输入品牌"></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item label="状态" prop="state">
              <el-select size="mini" v-model="options.state" clearable placeholder="事件状态">
                <el-option :label="name" :value="code" v-for="(name,code) in evtStatus"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="事件类型" prop="eventTypeTwoCode">
              <el-select size="mini" v-model="options.eventTypeTwoCode" clearable placeholder="事件类型">
                <el-option v-for="(label,k) in evtTypes" :label="label" :value="k" :key="k"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属中心" prop="group">
              <el-select size="mini" v-model="options.group" clearable placeholder="所属中心">
                <el-option v-for="(v,k) in dict['center']" :label="v" :value="k" :key="k"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分组" prop="groupType">
              <el-select v-model="options.groupType" placeholder="请选择分组类型" size="mini">
                <el-option
                  v-for="(value,key) in groups"
                  :key="key"
                  :label="value"
                  :value="key">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="groupValue">
              <el-input v-model="options.groupValue" placeholder="请输入分组名称" size="mini" class="mh5" clearable></el-input>
            </el-form-item>
            <!--            <el-form-item label="联系人" prop="contact">-->
            <!--              <el-input size="mini" v-model="options.brand" clearable placeholder="请输入联系人"></el-input>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="电话" prop="tel">-->
            <!--              <el-input size="mini" v-model="options.brand" clearable placeholder="请输入联系电话"></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item label="日期范围" prop="timeSpace">
              <el-date-picker
                v-model="options.timeSpace"
                type="daterange"
                align="right"
                unlink-panels
                size="mini"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="loadVideoList(1)">查询</el-button>
              <el-button size="mini" @click="resetOption('optionForm')">重置</el-button>
              <!-- <el-button size="mini" type="warning" @click="exportTab">导出表格</el-button> -->
            </el-form-item>
          </el-form>
        </div>
        <div class="page noBlueBg" slot="bottom">
          <el-pagination
            @size-change="changeSize"
            @current-change="changePage"
            :page-sizes="[20, 50, 100, 200]"
            :current-page="page"
            :page-size="limit"
            layout="sizes,total,prev, pager, next, jumper"
            :total="totals">
          </el-pagination>
        </div>
      </TableList>
      <WinPanel v-show="panelShow" :closePanel="closePanel" :data="panelData"/>

    </div>

    <!--    <div class="tools">-->
    <!--      <el-button type="primary" size="small" @click="mode='chart'" :class="{active:mode==='chart'}">-->
    <!--        <span class="iconfont" :class="icons.chart"></span>图表模式-->
    <!--      </el-button>-->
    <!--      <br>-->
    <!--      <el-button type="primary" size="small" @click="mode='table'" :class="{active:mode==='table'}">-->
    <!--        <span class="iconfont" :class="icons.table"></span>表格模式-->
    <!--      </el-button>-->
    <!--    </div>-->

    <Dialog :cfg="dialogCfg" ref="dialog2">
      <Map ref="map"></Map>
    </Dialog>

    <!--    工单详情-->
    <Dialog :cfg="infoDialogCfg" ref="infoDialog">
      <OrderInfo :data2="orderInfo" :pre="orderInfoPre"></OrderInfo>
    </Dialog>

  </section>
</template>

<script>
  import Module from 'comp/common/Module.vue';
  import TableList from 'comp/common/TableList3';
  import Dialog from 'comp/common/Dialog';
  import Map from 'comp/common/Map';
  import WinPanel from 'comp/common/WinPanel';
  import OrderInfo from 'comp/common/OrderInfo';

  export default {
    name: "CheckData",
    components: {
      Module,
      TableList,
      Dialog,
      Map,
      WinPanel,
      OrderInfo
    },
    data() {
      return {
        orderInfo: {},
        orderInfoPre: {},
        infoDialogCfg: {
          width: 700,
          height: 400,
          title: '工单详情',
          footerShow: !!0,
          closeShow: !!1
        },
        identityId: this.$kkui.cache.get('user')['identityId'],
        dict: this.$kkui.cache.get('dict'),
        mode: 'table',
        icons: WebCfg.icons,
        panelShow: false,
        panelData: {},

        moduleCfg: {
          allCameraInfo: {
            icon: WebCfg.icons.allCameraInfo,
            title: `摄像机运行总览`
          },
          errorCameraInfo: {
            icon: WebCfg.icons.errorCameraInfo,
            title: `摄像机故障类型分布`
          },
          brandErrorInfo: {
            icon: WebCfg.icons.brandErrorInfo,
            title: `各品牌摄像机故障统计`
          },
          errorAndFixCount: {
            icon: WebCfg.icons.errorAndFixCount,
            title: `本月摄像机故障发生及修复统计`
          },
        },
        charts: {},
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },

        options: {
          name: '',
          state: '',
          startTime: '',
          endTime: '',
          timeSpace: [],
          eventTypeTwoCode: '',
          group: '',
          groupType: '',
          groupValue: ''

        },

        list: [],
        column: [
          {
            prop: 'road',
            label: '路段'
          },
          {
            prop: 'location',
            label: '位置'
          },
          {
            prop: 'status',
            label: '状态'
          },
          // {
          //   prop: 'code',
          //   label: '路线编码'
          // },
          // {
          //   prop: 'powerModel',
          //   label: '取电方式'
          // },
          {
            prop: 'belong',
            label: '管理单位'
          },
          {
            prop: 'contac',
            label: '联系人'
          },

          {
            prop: 'tel',
            label: '联系电话'
          }
        ],
        dialogCfg: {
          width: 600,
          height: 400,
          title: '',
          closeShow: !!1,
          footerShow: !!1,
          submit: () => {
          }
        },
        multFlag: false,
        note: '',
        evtType: '',
        // evtTypes: '',

        limit: 20,
        page: 1,
        pages: 1,
        totals: 0,
        groups: this.$kkui.cache.get('dict')['cameraGroup'],
        evtStatus: this.$kkui.cache.get('dict')['status']

      }
    },
    created() {
      this.$server('camera.fault').then(data => {
        // this.$kkui.loading_deepBlue.hide();
        // this.loadAllCameraInfoChart(data['cameraTjList']);
        // this.loadErrorCameraInfoChart(data['cameraFaultList']);
        // this.loadBrandErrorInfoChart(data['brandFaultList']);
        // this.loadErrorAndFixCountChart(data['faultList'], data['repairList']);
        this.loadVideoList();
      })
    },
    computed: {
      evtTypes() {
        let data = this.$kkui.cache.get('dict')['event'];
        for (let key in data) {
          data[key] = data[key].indexOf('-') > -1 ? data[key].split('-')[1] : data[key];
        }
        return {'-1': '无事件', ...data};
      }
    },
    methods: {
      viewInfo(cell) {
        this.$server('monitor.orderInfo', {eventInfoId: cell.id}).then(data => {
          this.orderInfo = data;
          this.orderInfoPre = {...cell, infoType: 'event'};
          this.$refs.infoDialog.show = 1;
        })
      },
      getEvtName(name) {
        return name = name.indexOf('-') > -1 ? name.split('-')[1] : name;
      },
      getTypeName(code) {
        return this.groups[code]
      },
      //加载列表
      loadVideoList(firstPageFlag) {
        if (firstPageFlag) this.page = 1;
        //超级管理员id=1，后续对超管用户控制不可删除，以防止用户误删
        if (this.$kkui.cache.get('user')['roleId'] != 1) {
          // console.log(this.$kkui.cache.get('user')['deptId']);
          //this.options.group = this.$kkui.cache.get('user')['deptId'];
        }
        this.$server('monitor.list2', {
          limit: this.limit,
          page: this.page,
          ...this.options,
          ...{
            startTime: this.options.timeSpace ? this.options.timeSpace[0] : ''
          },
          ...{
            endTime: this.options.timeSpace ? this.options.timeSpace[1] : ''
          },
        }).then(data => {

          this.list = data['records'];
          this.totals = data['total'];
          this.$kkui.loading_deepBlue.hide();
        })
      },


      // 加载所有摄像机总览
      loadAllCameraInfoChart(data) {
        const $divDOM = document.querySelector('#allCameraInfo .content > div');
        const hBarData = {name: [], value: []};
        data.forEach(item => {
          hBarData.name.push(item.name);
          hBarData.value.push(item.value);
        });
        const hBarChart = this.$kkCharts.loadHBarChart(this.$echarts, $divDOM, hBarData, {
          left: 30,
          right: 30,
          barWidth: 50,
          labelFontSize: 20,
          fontBottom: 30,
          numBottom: 30,
          allNum: data.reduce((count, cur) => {
            return count + cur['value']
          }, 0),
          unit: '台'
        });
        if (!this.charts[hBarChart.id]) {
          this.charts[hBarChart.id] = hBarChart;
        }
      },

      // 加载故障摄像机
      loadErrorCameraInfoChart(data) {
        const $divDOM = document.querySelector('#errorCameraInfo .content > div');
        const picChart = this.$kkCharts.loadPieChart(this.$echarts, $divDOM, data, {
          radius: ['55%', '80%'],
          legendFontSize: 18,
          legendRight: '10%',
          bigFontSize: 20,
          smallFontSize: 16,
          unit: '台'
        });
        if (!this.charts[picChart.id]) {
          this.charts[picChart.id] = picChart;
        }
      },

      // 加载品牌故障统计
      loadBrandErrorInfoChart(data) {
        const $divDOM = document.querySelector('#brandErrorInfo .content > div');
        const newData = {name: [], value: []};
        data.forEach(item => {
          newData.name.push(item['manufacturer']);
          newData.value.push(item['brandCount']);
        });

        const vBarChart = this.$kkCharts.loadVBarChart(this.$echarts, $divDOM, newData, {
          top: 30,
          bottom: 20,
          minInterval: 5,
          barWidth: 30,
          splitLineColor: '#666',
          axisLabelFontSize: 16
        });
        if (!this.charts[vBarChart.id]) {
          this.charts[vBarChart.id] = vBarChart;
        }
      },

      // 加载本月故障和修复统计
      loadErrorAndFixCountChart(errorData, fixData) {
        const $divDOM = document.querySelector('#errorAndFixCount .content > div');
        let values = [[], []];
        const getMonths = () => {
          const t = new Date(), y = t.getFullYear(), m = t.getMonth() + 1;
          let a = [];
          while (a.length < new Date(y, m, 0).getDate()) {
            if (WebCfg.api.mock) {
              values[0].push(Math.ceil(Math.random() * 20));
              values[1].push(Math.ceil(Math.random() * 10));
            }
            a.push(a.length + 1);
          }
          return a;
        };

        const newData = {
          name: ['故障', '修复'],
          label: getMonths(),
          value: values
        };


        const multLineChart = this.$kkCharts.loadMultLineChart(this.$echarts, $divDOM, newData, {
          splitLineColor: '#666',
          labelPrefix: new Date().getMonth() + 1 + '月',
          labelSuffix: '日'
        });
        if (!this.charts[multLineChart.id]) {
          this.charts[multLineChart.id] = multLineChart;
        }
      },


      exportTab() {
        const index = this.$kkui.loading.show();
        this.$server('camera.faultTable', {
          ...this.options
        }).then(data => {
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '事件汇总表.xls');
          document.body.appendChild(link);
          link.click()
        })
      },

      // 重置option
      resetOption(formName) {
        this.$refs[formName].resetFields();
        this.loadVideoList(1);
      },

      //切换分页
      changePage(page) {
        this.page = page;
        this.loadVideoList();
      },

      changeSize(limit) {
        this.limit = limit;
        this.loadVideoList();
      },
      // 清除图表
      clearCharts() {
        Object.keys(this.charts).forEach(id => {
          this.charts[id].timer && clearInterval(this.charts[id].timer);
          this.charts[id].dispose();
          delete this.charts[id];
        });
        this.charts = {};
      },

      send() {
        this.$kkui.alert({
          icon: 0,
          cont: '确定派单维修吗？',
          callback: () => {
            this.$kkui.msg({
              icon: 1,
              cont: '派单成功！'
            })
          }
        })
      },
      goTo(lng, lat) {
        this.dialogCfg = {
          title: '查看位置',
          closeShow: true,
          width: 615,
          height: 430,
          bg: true
        };

        this.$refs.dialog2.show = true;
        setTimeout(() => {
          this.$refs.map.addSimpleMarker(lng, lat);
        }, 1000)

      },
      examine(row) {
        const fn = (v) => {
          this.$server('monitor.examine', {
            id: row.id,
            isPassage: v
          }).then(data => {
            this.$kkui.msg({
              icon: 1,
              cont: '操作完成！'
            })
            this.loadVideoList();
          })
        };
        this.$kkui.alert({
          icon: '',
          title: '审核',
          cont: '请选择事件处理的结果？',
          btn0Txt: '通过',
          btn1Txt: '不通过',
          callback: () => {
            fn(1);
          },
          cancelCallback: () => {
            fn(0);
          }

        })
      },
      rowClick(row) {
        const item = JSON.parse(JSON.stringify(row));
        const camera = item['bscCamera'];
        if (camera) {
          const id = item.id,
            code = item['eventTypeTwoCode'],
            color = WebCfg.eventColor[code],
            gis = [camera['longitude'], camera['latitude']];
          let name = this.dict['event'][code];
          name = name.indexOf('-') > -1 ? name.split('-')[1] : name;

          const _cfg = {
            preData: item,
            id,
            type: 'event',
            videoPath: item.videoPath,
            imagePath: item.imgPath,
            event: code,
            state: item.state,
            items: [
              {
                key: 'type',
                label: '类型',
                value: name,
                color
              },
              {
                key: 'state',
                label: '状态',
                value: this.dict['status'][item.state],
                color
              },
              {
                key: 'road',
                label: '路段',
                value: camera['road'],
                color
              },
              {
                key: 'pos',
                label: '位置',
                value: camera['name'],
                color
              },
              {
                key: 'detectedTime',
                label: '时间',
                value: item['detectedTime'],
                color
              }
            ],
            callback: () => {
              this.loadVideoList();
            }
          };
          if (code === '002-007-002') {
            _cfg.items.splice(2, 0, {
              key: 'visiable',
              label: '能见度',
              value: item['distance'] + '米',
              color
            })
          }

          this.panelData = _cfg;
        } else {
          return false;
        }
        this.panelShow = !!1;
      },
      changeUnit() {
        this.$server('org.department', {
          company: this.curUnit,
        }, 1).then(data => {
          this.curDepartment = '';
          this.receive = '';
          this.departments = data;
        })
      },

      changeDepartment() {
        this.$server('org.user', {
          company: this.curUnit,
          department: this.curDepartment
        }, 2).then(data => {
          this.receive = '';
          this.receives = data;
        })
      },
      handle(status, flag) {
        const multFlag = this.checkedItems.length > 1;
        const do1 = () => { // 稽核
          this.$refs.dialog.show = true;
          this.dialogCfg.width = 287;
          this.dialogCfg.height = 230;
          this.dialogCfg.title = '稽核';
          this.dialogCfg.submit = () => {
            if (!this.evtType) {
              this.$kkui.msg({
                icon: 0,
                cont: '请选择稽核更改的类型！'
              });
              return false;
            }
            this.$kkui.alert({
              icon: 0,
              cont: multFlag ? '确定统一稽核这些事件类型吗？' : '确定稽核此事件类型吗？',
              callback: () => {

                this.$server('monitor.multEvtHandle.jihe', this.checkedItems.map(item => {
                  return {
                    eventTypeTwoCode: this.evtType,
                    note: this.note,
                    id: item.id
                  }
                })).then(data => {
                  this.$kkui.msg({
                    icon: 1,
                    cont: '事件稽核成功！'
                  });
                  this.note = '';
                  this.$refs.dialog.show = false;
                  this.checkedItems = [];
                  this.loadEventList(1);
                })
              }
            })
          };
        };

        const do2 = () => { // 忽略
          if (flag) {
            const multFlag = this.checkedItems.length > 1;
            this.$server('org.company').then(data => {
              this.units = data;
              this.$refs.dialog.show = true;
              this.dialogCfg.width = 550;
              this.dialogCfg.height = 270;
              this.dialogCfg.title = '发布';
              this.dialogCfg.submit = () => {
                if (!this.receive) {
                  this.$kkui.msg({
                    icon: 0,
                    cont: '必须选择消息推送的人员！'
                  })
                } else {
                  this.$kkui.alert({
                    icon: 0,
                    cont: multFlag ? '确定统一发布这些事件吗？' : '确定发布此事件吗？',
                    callback: () => {
                      this.$server('monitor.multEvtHandle.fabu', this.checkedItems.map(item => {
                        return {
                          pushInterface: false,
                          mobile: this.receive,
                          id: item.id
                        }
                      }), 1).then(data => {
                        this.$kkui.msg({
                          icon: 1,
                          cont: '事件发布成功！'
                        });
                        this.receive = '';
                        this.receives = [];
                        this.curDepartment = '';
                        this.departments = [];
                        this.units = [];
                        this.curUnit = '';
                        this.$refs.dialog.show = false;
                        this.checkedItems = [];
                        this.loadEventList(2);
                      })
                    }
                  })

                }
              };
            });
          } else {
            const multFlag = this.checkedItems.length > 1;
            this.$kkui.alert({
              icon: 0,
              cont: multFlag ? '确定统一忽略发布这些事件吗？' : '确定忽略发布此事件吗？',
              callback: () => {
                this.$server('monitor.multEvtHandle.hl', this.checkedItems.map(item => {
                  return {
                    pushInterface: false,
                    mobile: this.receive,
                    id: item.id
                  }
                }), 1).then(data => {
                  this.$kkui.msg({
                    icon: 1,
                    cont: '事件忽略成功！'
                  });
                  this.$refs.dialog.show = false;
                  this.checkedItems = [];
                  this.loadEventList(2);
                })
              }
            })
          }
        };
        [do1, do2][status - 1]();


      },
      closePanel() {
        this.panelShow = false;
      }
    },
  }
</script>

<style scoped lang="scss">
  @import "~css/monitor.scss";

  .tableBox {
    padding: 0 20px;
  }

  /deep/ .el-date-editor--daterange.el-input, .el-date-editor--daterange.el-input__inner, .el-date-editor--timerange.el-input, .el-date-editor--timerange.el-input__inner {
    width: 220px;
  }

  /deep/ .el-date-editor .el-range-input {
    width: 80px;
  }
</style>
